package com.zk.yygh.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zk.yygh.enums.OrderStatusEnum;
import com.zk.yygh.enums.PaymentStatusEnum;
import com.zk.yygh.enums.PaymentTypeEnum;
import com.zk.yygh.helper.HttpRequestHelper;
import com.zk.yygh.hosp.exception.HospitalException;
import com.zk.yygh.hosp.result.ResultCodeEnum;
import com.zk.yygh.hosp_client.service.HospFeignClient;
import com.zk.yygh.model.hosp.Schedule;
import com.zk.yygh.model.order.OrderInfo;
import com.zk.yygh.model.order.PaymentInfo;
import com.zk.yygh.model.user.Patient;
import com.zk.yygh.order.mapper.OrderMapper;
import com.zk.yygh.order.service.OrderService;
import com.zk.yygh.order.service.PaymentService;
import com.zk.yygh.order.service.WeiXinService;
import com.zk.yygh.user_client.service.UserFeignClient;
import com.zk.yygh.vo.hosp.ScheduleOrderVo;
import com.zk.yygh.vo.msm.MsmVo;
import com.zk.yygh.vo.order.*;
import com.zk.yygh.rabbit.constant.MqConst;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zk.yygh.rabbit.service.RabbitService;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: 张凯
 * @date: 2022/6/20 - 14:46
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderInfo> implements OrderService {

    //医院远程调用接口
    @Autowired
    private HospFeignClient hospFeignClient;

    //用户远程调用接口
    @Autowired
    private UserFeignClient userFeignClient;

    //微信接口
    @Autowired
    private WeiXinService weiXinService;

    //mq工具
    @Autowired
    private RabbitService rabbitService;

    @Autowired
    private PaymentService paymentService;


    //保存订单
    @Override
    public Long saveOrder(String scheduleId, Long patientId) {
        //获取就诊人信息
        Patient patient = userFeignClient.getPatientById(patientId);
        if (patient == null) {
            throw new HospitalException(ResultCodeEnum.PARAM_ERROR);
        }
        //获取预约订单信息
        ScheduleOrderVo scheduleOrderVo = hospFeignClient.getScheduleOrderVo(scheduleId);
        if (scheduleOrderVo == null) {
            throw new HospitalException(ResultCodeEnum.PARAM_ERROR);
        }
        //获取下单引用的签名信息
        SignInfoVo signInfoVo = hospFeignClient.getSignInfoVo(scheduleOrderVo.getHoscode());
        if (signInfoVo == null) {
            throw new HospitalException(ResultCodeEnum.PARAM_ERROR);
        }
        //判断当前时间可否预约
        if (new DateTime(scheduleOrderVo.getStartTime()).isAfterNow()
                || new DateTime(scheduleOrderVo.getEndTime()).isBeforeNow()) {
            throw new HospitalException(ResultCodeEnum.TIME_NO);
        }
        //创建订单信息对象并封装属性
        OrderInfo orderInfo = new OrderInfo();
        BeanUtils.copyProperties(scheduleOrderVo, orderInfo);
        String outTradeNo = System.currentTimeMillis() + "" + new Random().nextInt(100);
        orderInfo.setOutTradeNo(outTradeNo);    //订单交易号为自己生成
        orderInfo.setScheduleId(scheduleOrderVo.getHosScheduleId());
        orderInfo.setUserId(patient.getUserId());
        orderInfo.setPatientId(patientId);
        orderInfo.setPatientName(patient.getName());
        orderInfo.setPatientPhone(patient.getPhone());
        orderInfo.setOrderStatus(OrderStatusEnum.UNPAID.getStatus());
        //添加订单信息
        this.save(orderInfo);
        //封装调用医院平台方参数
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("hoscode", orderInfo.getHoscode());
        paramMap.put("depcode", orderInfo.getDepcode());
        paramMap.put("hosScheduleId", orderInfo.getScheduleId());
        paramMap.put("reserveDate", new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd"));
        paramMap.put("reserveTime", orderInfo.getReserveTime());
        paramMap.put("amount", orderInfo.getAmount());
        paramMap.put("name", patient.getName());
        paramMap.put("certificatesType", patient.getCertificatesType());
        paramMap.put("certificatesNo", patient.getCertificatesNo());
        paramMap.put("sex", patient.getSex());
        paramMap.put("birthdate", patient.getBirthdate());
        paramMap.put("phone", patient.getPhone());
        paramMap.put("isMarry", patient.getIsMarry());
        paramMap.put("provinceCode", patient.getProvinceCode());
        paramMap.put("cityCode", patient.getCityCode());
        paramMap.put("districtCode", patient.getDistrictCode());
        paramMap.put("address", patient.getAddress());
        //联系人
        paramMap.put("contactsName", patient.getContactsName());
        paramMap.put("contactsCertificatesType", patient.getContactsCertificatesType());
        paramMap.put("contactsCertificatesNo", patient.getContactsCertificatesNo());
        paramMap.put("contactsPhone", patient.getContactsPhone());
        paramMap.put("timestamp", HttpRequestHelper.getTimestamp());
        //------>签名注意<-----
        String sign = signInfoVo.getSignKey();
        paramMap.put("sign", sign);
        //向医院方执行调用
        JSONObject result = HttpRequestHelper.sendRequest(paramMap, signInfoVo.getApiUrl() + "/order/submitOrder");
        //对返回结果进行判别
        if (result.getInteger("code") == 200) {
            JSONObject jsonObject = result.getJSONObject("data");
            //预约记录唯一标识（医院预约记录主键）
            String hosRecordId = jsonObject.getString("hosRecordId");
            //预约序号
            Integer number = jsonObject.getInteger("number");
            ;
            //取号时间
            String fetchTime = jsonObject.getString("fetchTime");
            ;
            //取号地址
            String fetchAddress = jsonObject.getString("fetchAddress");
            ;
            //更新订单
            orderInfo.setHosRecordId(hosRecordId);
            orderInfo.setNumber(number);
            orderInfo.setFetchTime(fetchTime);
            orderInfo.setFetchAddress(fetchAddress);
            baseMapper.updateById(orderInfo);
            //排班可预约数
            Integer reservedNumber = jsonObject.getInteger("reservedNumber");
            //排班剩余预约数
            Integer availableNumber = jsonObject.getInteger("availableNumber");
            //发送mq信息更新号源和短信通知
            //MQ消息封装：更新号源
            OrderMqVo orderMqVo = new OrderMqVo();
            orderMqVo.setScheduleId(scheduleId);
            orderMqVo.setReservedNumber(reservedNumber);
            orderMqVo.setAvailableNumber(availableNumber);

            //短信提示
            MsmVo msmVo = new MsmVo();
            msmVo.setPhone(orderInfo.getPatientPhone());
//            msmVo.setTemplateCode("SMS_154950909");
            String reserveDate =
                    new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd")
                            + (orderInfo.getReserveTime() == 0 ? "上午" : "下午");
            Map<String, Object> param = new HashMap<String, Object>() {{
                put("title", orderInfo.getHosname() + "|" + orderInfo.getDepname() + "|" + orderInfo.getTitle());
                put("amount", orderInfo.getAmount());
                put("reserveDate", reserveDate);
                put("name", orderInfo.getPatientName());
                put("quitTime", new DateTime(orderInfo.getQuitTime()).toString("yyyy-MM-dd HH:mm"));
            }};
            msmVo.setParam(param);
            //给MQ消息设置短信实体
            orderMqVo.setMsmVo(msmVo);
            //调用mq工具发送短信
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER, MqConst.ROUTING_ORDER, orderMqVo);
        } else {
            throw new HospitalException(result.getString("message"), ResultCodeEnum.FAIL.getCode());
        }
        return orderInfo.getId();
    }

    //订单列表（订单查询带分页）
    @Override
    public IPage<OrderInfo> orderInfoList(Page<OrderInfo> pageParam, OrderQueryVo orderQueryVo) {
        //orderQueryVo获取条件值
        String name = orderQueryVo.getKeyword(); //医院名称
        Long patientId = orderQueryVo.getPatientId(); //就诊人id
        String orderStatus = orderQueryVo.getOrderStatus(); //订单状态
        String reserveDate = orderQueryVo.getReserveDate();//安排时间
        String createTimeBegin = orderQueryVo.getCreateTimeBegin();
        String createTimeEnd = orderQueryVo.getCreateTimeEnd();
        //进行条件封装
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(name)) {
            //对医院名字进行模糊查询
            wrapper.like("hosname", name);
        }
        if (!StringUtils.isEmpty(patientId)) {
            //对就诊人Id进行等值查询
            wrapper.eq("patient_id", patientId);
        }
        if (!StringUtils.isEmpty(orderStatus)) {
            //对订单状态进行等值查询
            wrapper.eq("order_status", orderStatus);
        }
        if (!StringUtils.isEmpty(reserveDate)) {
            //对安排时间进行范围查询
            wrapper.ge("reserve_time", reserveDate);
        }
        //对创建时间进行范围查询
        if (!StringUtils.isEmpty(createTimeBegin)) {
            wrapper.ge("create_time", createTimeBegin);
        }
        if (!StringUtils.isEmpty(createTimeEnd)) {
            wrapper.ge("create_time", createTimeEnd);
        }
        //执行查询
        IPage<OrderInfo> iPage = baseMapper.selectPage(pageParam, wrapper);
        //获取查询出的结果
        List<OrderInfo> orderInfoList = iPage.getRecords();
        //对查询结果进行状态封装
        orderInfoList.stream().forEach(item -> this.fullInfo(item));
        return iPage;
    }

    @Override
    public OrderInfo getOrder(Long orderId) {
        OrderInfo orderInfo = this.getById(orderId);
        this.fullInfo(orderInfo);
        return orderInfo;
    }

    //取消订单
    @Override
    public boolean cancelOrder(Long orderId) {
        //获取订单信息
        OrderInfo orderInfo = getOrder(orderId);
        //获取支付信息
        PaymentInfo paymentInfo = paymentService.getPayment(orderId, PaymentTypeEnum.WEIXIN.getStatus());
        //判断是否超时->进行取消预约
        DateTime quitTime = new DateTime(orderInfo.getQuitTime());
        if (quitTime.isBeforeNow()) {
            throw new HospitalException(ResultCodeEnum.CANCEL_ORDER_NO);
        }
        //获取医院签名->封装参数->执行请求（更新订单支付状态【取消预约】）
        SignInfoVo signInfoVo = hospFeignClient.getSignInfoVo(orderInfo.getHoscode());
        if (signInfoVo == null) {
            throw new HospitalException(ResultCodeEnum.PARAM_ERROR);
        }
        Map<String, Object> reqMap = new HashMap<>();
        reqMap.put("hoscode", orderInfo.getHoscode());
        reqMap.put("hosRecordId", orderInfo.getHosRecordId());
        reqMap.put("timestamp", HttpRequestHelper.getTimestamp());
        reqMap.put("sign", signInfoVo.getSignKey());
        JSONObject result = HttpRequestHelper.sendRequest(reqMap, signInfoVo.getApiUrl() + "/order/updateCancelStatus");
        //对返回的结果码进行判断是否已支付
        if (result.getInteger("code") != 200) {
            throw new HospitalException(result.getString("message"), ResultCodeEnum.FAIL.getCode());
        } else {
            //是否支付进行退款
            if (orderInfo.getOrderStatus().intValue() == OrderStatusEnum.PAID.getStatus()) {
                //已支付->进行退款操作（orderId）
                boolean isRefund = weiXinService.refund(orderId);
            }
            //更新订单状态
            orderInfo.setOrderStatus(OrderStatusEnum.CANCLE.getStatus());
            this.updateById(orderInfo);
            //发送mq消息更新预约数
            OrderMqVo orderMqVo = new OrderMqVo();
            orderMqVo.setScheduleId(orderInfo.getScheduleId());
            //短信提示
            MsmVo msmVo = new MsmVo();
            msmVo.setPhone(orderInfo.getPatientPhone());
//            msmVo.setTemplateCode("SMS_194640722");
            String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + (orderInfo.getReserveTime() == 0 ? "上午" : "下午");
            Map<String, Object> param = new HashMap<String, Object>() {{
                put("title", orderInfo.getHosname() + "|" + orderInfo.getDepname() + "|" + orderInfo.getTitle());
                put("reserveDate", reserveDate);
                put("name", orderInfo.getPatientName());
            }};
            msmVo.setParam(param);
            //设置短信消息
            orderMqVo.setMsmVo(msmVo);
            //取消预约更新预约数 TODO:调用医院方进行更新排班信息
//            Schedule schedule = hospFeignClient.getScheduleById(orderMqVo.getScheduleId());
//            int availableNumber = schedule.getAvailableNumber().intValue() + 1;
//            schedule.setAvailableNumber(availableNumber);
//            hospFeignClient.updateSchedule(schedule);
            //mq发送消息
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER, MqConst.ROUTING_ORDER, orderMqVo);
        }
        return true;
    }

    //定时任务提醒就诊人
    @Override
    public void patientTips() {
        //获取订单信息列表
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        //匹配当天日期
        wrapper.eq("reserve_date", new DateTime().toString("yyyy-MM-dd"));
        wrapper.ne("order_status", OrderStatusEnum.UNPAID);
        wrapper.ne("order_status", OrderStatusEnum.CANCLE);
        //遍历订单信息列表
        List<OrderInfo> orderInfoList = baseMapper.selectList(wrapper);
        System.out.println(orderInfoList);
        for (OrderInfo orderInfo : orderInfoList) {
            //封装短信提醒内容并发送短信
            MsmVo msmVo = new MsmVo();
            //设置就诊人电话
            msmVo.setPhone(orderInfo.getPatientPhone());
            //获取安排的日期
            String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd")
                    + (orderInfo.getReserveTime() == 0 ? "上午" : "下午");
            //给短信实体设置相关参数
            Map<String, Object> param = new HashMap<String, Object>() {{
                put("title", orderInfo.getHosname() + "|" + orderInfo.getDepname() + "|" + orderInfo.getTitle());
                put("reserveDate", reserveDate);
                put("name", orderInfo.getPatientName());
            }};
            msmVo.setParam(param);
            //发送短信消息让短信的接收器接收进行发送
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_MSM,MqConst.ROUTING_MSM_ITEM,msmVo);
        }
    }

    @Override
    public Map<String,Object> getReserveDateMap(OrderCountQueryVo orderCountQueryVo) {
        List<OrderCountVo> reserveDateMap = this.baseMapper.getReserveDateMap(orderCountQueryVo);
        //获取x轴统计日期
        List<String> reserveDateList = reserveDateMap.stream().map(OrderCountVo::getReserveDate).collect(Collectors.toList());
        //获取y轴统计数量
        List<Integer> countList = reserveDateMap.stream().map(OrderCountVo::getCount).collect(Collectors.toList());
        //封装数据
        Map<String,Object> map=new HashMap<>();
        map.put("dateList",reserveDateList);
        map.put("countList",countList);
        return map;
    }

    //订单详情
    @Override
    public Map<String, Object> show(Long orderId) {
        Map<String, Object> map = new HashMap<>();
        OrderInfo orderInfo = this.getById(orderId);
        this.fullInfo(orderInfo);
        map.put("orderInfo", orderInfo);
        Patient patient
                =  userFeignClient.getPatientById(orderInfo.getPatientId());
        map.put("patient", patient);
        return map;
    }

    private void fullInfo(OrderInfo orderInfo) {
        orderInfo.getParam().put("orderStatusString", OrderStatusEnum.getStatusNameByStatus(orderInfo.getOrderStatus()));
    }
}
